"""
模板加载模块 / Template loading module
负责从仓库的 .gitcode 目录读取 Issue 与 PR 模板。
"""
import os
from pathlib import Path
from typing import Optional


class TemplateLoader:
    """
    模板加载器 / Template loader
    """
    
    LANGUAGE_HINTS = {
        "zh": ("zh", "cn", "chinese"),
        "en": ("en", "english"),
    }
    
    def __init__(self, repo_path: Path, language: str = "zh"):
        """
        初始化模板加载器 / Initialize the template loader.
        :param repo_path: 仓库路径 / Repository root path
        :param language: 语言偏好（默认中文）/ Preferred language (defaults to Chinese)
        """
        self.repo_path = Path(repo_path)
        self.gitcode_path = self.repo_path / ".gitcode"
        self.language = language if language in self.LANGUAGE_HINTS else "zh"

    def _select_file_by_language(self, files):
        """
        根据语言提示选择模板文件 / Select template file according to language hints.
        :param files: 文件列表 / Candidate files
        :return: 匹配的文件或第一个文件 / Matched file or first entry
        """
        if not files:
            return None
        hints = self.LANGUAGE_HINTS.get(self.language, ())
        lower_map = {f: f.name.lower() for f in files}
        for hint in hints:
            for file, name in lower_map.items():
                if hint in name:
                    return file
        return files[0]
    
    def get_issue_template(self) -> Optional[str]:
        """
        获取 Issue 模板内容 / Fetch Issue template content.
        优先查找 .md 文件，如果没有则查找 .yml 文件并提取 body 部分。
        :return: 模板内容（可能为 None）/ Template content or None
        """
        issue_template_dir = self.gitcode_path / "ISSUE_TEMPLATE"
        
        if not issue_template_dir.exists():
            return None
        
        md_files = list(issue_template_dir.glob("*.md"))
        template_file = self._select_file_by_language(md_files)
        if template_file:
            try:
                with open(template_file, 'r', encoding='utf-8') as f:
                    return f.read()
            except Exception:
                pass
        
        # 查找 .yml 文件，提取 body 部分
        # 对于 YAML 格式的模板，我们返回一个简化版本
        # 因为完整的 YAML 模板包含表单字段，不适合直接作为 body
        yml_files = [f for f in issue_template_dir.glob("*.yml") if f.name != "config.yml"]
        if yml_files:
            # 对于 YAML 模板，返回一个提示，说明这是基于模板的
            # 实际使用时，用户可能需要手动填写表单
            return None  # YAML 模板不适合直接作为 body，返回 None 让用户自己填写
        
        return None
    
    def get_issue_template_path(self) -> Optional[str]:
        """
        获取 Issue 模板路径（相对于仓库根目录）/ Get Issue template path relative to repo root.
        优先查找 .md 文件，如果没有则查找 .yml 文件。
        :return: 模板路径或 None / Template path or None
        """
        issue_template_dir = self.gitcode_path / "ISSUE_TEMPLATE"
        
        if not issue_template_dir.exists():
            return None
        
        md_files = list(issue_template_dir.glob("*.md"))
        template_file = self._select_file_by_language(md_files)
        if template_file:
            return str(template_file.relative_to(self.repo_path))
        
        yml_files = [f for f in issue_template_dir.glob("*.yml") if f.name != "config.yml"]
        template_file = self._select_file_by_language(yml_files)
        if template_file:
            return str(template_file.relative_to(self.repo_path))
        
        return None
    
    def get_pr_template(self) -> Optional[str]:
        """
        获取 PR 模板内容 / Fetch PR template content.
        :return: 模板内容或 None / Template content or None
        """
        pr_template_dir = self.gitcode_path / "PULL_REQUEST_TEMPLATE"
        
        if not pr_template_dir.exists():
            return None
        
        md_files = list(pr_template_dir.glob("*.md"))
        template_file = self._select_file_by_language(md_files)
        if template_file:
            try:
                with open(template_file, 'r', encoding='utf-8') as f:
                    return f.read()
            except Exception:
                pass
        
        return None
    
    def append_issue_url(self, template: str, issue_url: str) -> str:
        """
        在模板内容后面添加 Issue URL / Append Issue URL to template content.
        :param template: 模板内容 / Template text
        :param issue_url: Issue URL
        :return: 新模板内容 / Updated template text
        """
        if not template:
            return f"\n\nRelated Issue: {issue_url}"
        
        placeholders = [
            "请填写此Pull Request要关联的issue链接。",
            "Please provide links to issues related to this Pull Request."
        ]
        replaced = False
        for placeholder in placeholders:
            if placeholder in template:
                template = template.replace(placeholder, issue_url)
                replaced = True
        if replaced:
            return template

        # 在模板末尾添加 Issue URL
        return f"{template}\n\n---\n\nRelated Issue: {issue_url}"


def get_commit_first_line(repo_path: Path, branch: str = "HEAD") -> Optional[str]:
    """
    获取指定分支的最新 commit 的第一行（作为 PR 标题）/ Get first line of latest commit.
    :param repo_path: 仓库路径 / Repository path
    :param branch: 分支名（默认 HEAD）/ Branch name (defaults to HEAD)
    :return: commit 第一行或 None / Commit subject or None
    """
    import subprocess
    
    try:
        result = subprocess.run(
            ["git", "log", "-1", "--pretty=format:%s", branch],
            cwd=repo_path,
            capture_output=True,
            text=True
        )
        if result.returncode == 0 and result.stdout.strip():
            return result.stdout.strip()
    except Exception:
        pass
    
    return None

